<?php

class Front_controller extends MY_Controller {

//    function checkUrl(){
//        $url = $_SERVER['REQUEST_URI'];
//        preg_match('/\/([^\/]*$)/i', $url, $matches);        
//        if ($matches[1]!=''&&!preg_match("/html$/i",$matches[1])){
//               header('Location: '.base_url().'404.html');
//        }        
//    }
    function _remap($method, $params) {
        // $this->checkUrl();
        $this->load->model('Page');
        switch (count($params)) {
            case 0:
                $curPage = $this->Page->get_by_field(array('home' => 1), '*', true);
                break;
            default:
                $curPage = $this->Page->get_by_field(array('url' => $params[0]), '*', true);
        }
        if (empty($curPage)) {
            //$this->load->model('Language');
            //$language = (isset($params[0])&&$this->Language->check_isset(array('language_code'=>$params[0])))?$params[0]:config_item('default_language');
            $curPage = $this->Page->get_by_field(array('error' => 1), '*', true);
        }
        //-------Support Online-----
      
        $curPage['elements'] = unserialize($curPage['elements']);
        $this->$curPage['action']($curPage, $params);
    }

    function static_page($curPage, $params) {
        $this->_setLayout("front/{$curPage['template']}", 'front_layout', $curPage);
    }

    function home_page($curPage, $params) {
        $this->load->model('Products_model');
        $curPage = array_merge($curPage, array(
            'product' => $this->Products_model->getInHomeProduct(),
            'product_no_sale' => $this->Products_model->getProductNoSale()
                ));
        $this->_setLayout("front/{$curPage['template']}", 'front_layout', $curPage);
    }

    function product($curPage, $params) {
        /* @var $productOb Products_model */
        $this->load->model('Products_model');
        $productOb = $this->Products_model;
        /* @var $cateOb cate_model */
        $this->load->model('cate_model');
        $cateOb = $this->cate_model;
        switch (count($params)) {
            case 2: {                  
                    $cateItem = $cateOb->get_by_id($params[1]);
                    $curPage = array_merge($curPage, array(
                        'recipe_list' => $productOb->get_list(null, null, 'order', 'ASC',"category_id = '{$params[1]}'"),
                        'cateItem' => $cateItem
                        ));
                    $this->_setLayout("front/extend/category", 'front_layout', $curPage);
                    break;
                }
            default: {
                die('Error');
                    preg_match("/(\d+)-*(.*)/i", $params[1], $match);
                    $pID = $match[1];
                    $pAlias = $match[2];
                    $curPage['item'] = $this->Products_model->get_by_id($pID);

                    if (empty($curPage['item']) || $pAlias != $curPage['item']['alias']) {
                        header('Location: ' . base_url() . '404.html');
                    }

                    $pList = $this->Products_model->get_list(null, null, 'order', 'ASC');

                    $curPage['pList'] = $pList;
                    $this->_setLayout("front/extend/product_detail", 'front_layout', $curPage);
                    break;
                }
        }
    }

//	function news($curPage,$params)
//	{			
//			$page = 1;
//			$news_home = true;
//			switch(count($params)){
//				case 2:
//					$this->load->model('News');
//					$curPage['news_details'] = $this->News->get_by_field(array('url'=>$params[1]),'*',true);
//					if(!empty($curPage['news_details'])){ 
//						$curPage['title'] .= " | {$curPage['news_details']['title']}";
//						$curPage['description'] .= ", {$curPage['news_details']['title']}";
//						$curPage['type'] = 'details';
//						$this->_setLayout("front/{$curPage['template']}",'front_layout',$curPage);
//						break;	
//					}
//				case 3:
//					$news_home = false;
//					$page = ($params[1]=='page'&&is_numeric($params[2]))?$params[2]:1;
//				default:
//					$this->load->model('News');		
//					$total_rows = $this->News->get_total();
//					$limit = 4;
//					$start = ( $page - 1 ) * $limit;
//                                        $this->load->library('paginator',array(
//                                            'link' => '/news/page',
//                                            'totalrecord' => $total_rows,
//                                            'itemPerPage' => $limit
//                                        ));
//
//                                        $newslist = $this->News->get_list($start,$limit,$sort= 'date',$dir='DESC');
//                                        if(count($newslist)<=0){
//                                             header('Location: '.base_url().'404.html');
//                                        }
//
//					$curPage = array_merge($curPage,array('pagination'=>$this->paginator->create($page),
//								  						  'news_list'=>$newslist));
//					if(!$news_home){
//						$curPage['title'] .= " | $page";
//						$curPage['description'] .=  " Page $page";
//					}
//					$curPage['type'] = 'list';
//					$this->_setLayout("front/{$curPage['template']}",'front_layout',$curPage);	
//			}
//	}		

    function contact_us($curPage, $params) {
        $curPage['result'] = false;
        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            if ($this->input->post('captcha_input') && strtolower($this->input->post('captcha_input')) == strtolower($this->session->userdata('captcha_word'))) {
                $email_list = array();
                $this->load->model('Email');
                $email_list = $this->Email->get_all_email();
                $this->load->library('phpmailer');
                $this->phpmailer->IsSMTP();
                $this->phpmailer->SMTPAuth = config_item('smtp_auth');                  // enable SMTP authentication
                $this->phpmailer->SMTPSecure = config_item('smtp_secure');                 // sets the prefix to the servier
                $this->phpmailer->Host = config_item('smtp_host');      // sets GMAIL as the SMTP server                        
                $this->phpmailer->Port = config_item('smtp_port');                   // set the SMTP port for the GMAIL server
                $this->phpmailer->Username = config_item('smtp_username');  // GMAIL username
                $this->phpmailer->Password = config_item('smtp_password');            // GMAIL password
                $this->phpmailer->AddReplyTo($_POST['email'], $_POST['name']);
                $this->phpmailer->From = $_POST['email'];
                $this->phpmailer->FromName = $_POST['name'];
                $this->phpmailer->Sender = config_item('smtp_username');
                $this->phpmailer->Subject = 'Thông Tin Liên Hệ từ website '.$_POST['name'];
                $this->phpmailer->WordWrap = 50; // set word wrap
                $this->phpmailer->SMTPDebug = 1;
                foreach ($email_list as $row) {
                    $this->phpmailer->AddAddress($row['email'], $row['name']);
                }
                $msgHtml = "Name: {$_POST['name']}<br>
                                    Email: {$_POST['email']}<br>
                                    Address: {$_POST['address']}<br>                                   
                                    Phone: {$_POST['phone']}<br>
                                    Fax: {$_POST['fax']}<br>
                                   " . nl2br($_POST['comment']);
                $this->phpmailer->MsgHTML($msgHtml);
                $this->phpmailer->IsHTML(true); // send as HTML
                if ($this->phpmailer->Send()) {
                    $curPage['result'] = true;
                    $this->load->model('Contact');
                } else {
                    die($this->phpmailer->ErrorInfo);
                }
            } else {
                $curPage['message'] = 'Captcha not correct';
            }
        }
        $this->load->helper('captcha');
        $vals = array(
            'word' => $this->genRandomString(),
            'img_path' => getcwd() . '/public/captcha/',
            'img_url' => base_url() . 'public/captcha/',
            'font_path' => getcwd() . '/public/fonts/captcha2.ttf',
            'img_width' => '125',
            'img_height' => 80,
            'expiration' => 7200
        );

        $cap = create_captcha($vals);
        $curPage['captcha'] = $cap;
        $this->session->set_userdata('captcha_word', $cap['word']);
        $this->_setLayout("front/{$curPage['template']}", 'front_layout', $curPage);
    }
    
    function order($curPage, $params) {
        $this->load->model('Products_model');
        $productOb = $this->Products_model;
        $product = $productOb->get_by_id($params[1]);
        $curPage['product'] = $product;
        $curPage['result'] = false;
        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            //Save In DB --------------------------
         
                $this->load->model('Order_model');
                /* @var $orderOb Order_model */
                $orderOb = $this->Order_model;
                $oData = array(
                    'ten_sp' => $product['name'],
                    'soluong' => $_POST['soluong'],
                    'gia' => $_POST['price'],
                    'tenkhachhang' => $_POST['name'],
                    'email' => $_POST['email'],
                    'dien_thoai' => $_POST['phone'],
                    'mota' => $_POST['comment'],
                    'order_date' => date('Y-m-d'),
                    'trangthai' => 'New',
                    'diachi' => $_POST['address']
                );               
                $orderOb->insert($oData);
            //-------------------------------------
                $email_list = array();
                $this->load->model('Email');
                $email_list = $this->Email->get_all_email();
                $this->load->library('phpmailer');
                $this->phpmailer->IsSMTP();
                $this->phpmailer->SMTPAuth = config_item('smtp_auth');                  // enable SMTP authentication
                $this->phpmailer->SMTPSecure = config_item('smtp_secure');                 // sets the prefix to the servier
                $this->phpmailer->Host = config_item('smtp_host');      // sets GMAIL as the SMTP server                        
                $this->phpmailer->Port = config_item('smtp_port');                   // set the SMTP port for the GMAIL server
                $this->phpmailer->Username = config_item('smtp_username');  // GMAIL username
                $this->phpmailer->Password = config_item('smtp_password');            // GMAIL password
                $this->phpmailer->AddReplyTo($_POST['email'], $_POST['name']);
                $this->phpmailer->From = $_POST['email'];
                $this->phpmailer->FromName = $_POST['name'];
                $this->phpmailer->Sender = config_item('smtp_username');
                $this->phpmailer->Subject = $_POST['name'].'Đặt Hàng Online';
                $this->phpmailer->WordWrap = 50; // set word wrap
                $this->phpmailer->SMTPDebug = 1;
                foreach ($email_list as $row) {
                    $this->phpmailer->AddAddress($row['email'], $row['name']);
                }
                $msgHtml = "Name: {$_POST['name']}<br>
                            Email: {$_POST['email']}<br>                                                           
                            Phone: {$_POST['phone']}<br>
                            Fax: {$_POST['fax']}<br>
                            So Luong: {$_POST['soluong']}<br>
                            Dia Chi: {$_POST['soluong']}<br>
                            Ten San Pham: {$product['name']}<br>
                            Don Gia: {$product['price']}<br>                            
                                   " . nl2br($_POST['comment']);                            
                $this->phpmailer->MsgHTML($msgHtml);
                $this->phpmailer->IsHTML(true); // send as HTML
                if ($this->phpmailer->Send()) {
                    $curPage['result'] = true;
                    $this->load->model('Contact');
                } else {
                    die($this->phpmailer->ErrorInfo);
                }
        }
        /* @var $productOb Products_model */      
        
        $this->_setLayout("front/extend/order", 'front_layout', $curPage);
    }
}